library("shiny")
library("plotly")
library("dtw")
library("tidyr")

source("funkce.R")

ui=fluidPage(
  
  navbarPage("COHP",
  
  # tabPanel("Zobrazeni",
  #          plotlyOutput("grafik")
  #          
  # ),
  
  tabPanel("Korelace Stabilni",
           plotlyOutput("grafkorStabB"), 
           br(),
           plotlyOutput("vyberStabB")
  ),
  
  tabPanel("Korelace Nestabilni",
           plotlyOutput("grafkorNeStabB"),
           br(),
           plotlyOutput("vyberNeStabB")
  ),
  tabPanel("DTW Stabilni",
           plotlyOutput("grafDTWmindistSTAB"),
           br(),
           plotlyOutput("vyberdtw")
  ),
  tabPanel("DTW Nestabilni",
           plotlyOutput("grafDTWmindistNESTAB"),
           br(),
           plotlyOutput("vyberdtwN")
  ),
  tabPanel("Vzd?lenost Stabilni",
           plotlyOutput("grafDistBodStab"),
           br(),
           plotlyOutput("vyberDist")
  ),
  tabPanel("Vzdalenost Nestabilni",
           plotlyOutput("grafDistBodNestab"),
           br(),
           plotlyOutput("vyberDistN")
  ),
  tabPanel("DOKPHS Stabiln? Ni-Ni",
           plotlyOutput("outBarSnini"),
           br(),
           plotlyOutput("outPlotSnini")
  ),
  tabPanel("DOKPHS Stabiln? Si-Ni",
           plotlyOutput("outBarSsini"),
           br(),
           plotlyOutput("outPlotSsini")
  ),
  tabPanel("DOKPHS Nestabiln? Ni-Ni",
           plotlyOutput("outBarNnini"),
           br(),
           plotlyOutput("outPlotNnini")
  ),
  tabPanel("DOKPHS Nestabiln? Si-Ni",
           plotlyOutput("outBarNsini"),
           br(),
           plotlyOutput("outPlotNsini")
  )
)
)

server = function(input,output){
  val = reactiveValues(
    dfkrych = read.csv("Data/cohp-Bulk.csv",header=T, sep=",", dec="."),
    dfstab = read.csv("Data/cohp-GB-stable.csv",header=T, sep=",", dec="."),
    dfnestab = read.csv("Data/cohp-GB-unstable.csv",header=T, sep=",", dec=".")
  )
  
  output$grafik = renderPlotly({
      dfkrych = val$dfkrych
      dfstab = val$dfstab
      dfnestab = val$dfnestab
    #browser()
    #vykreslen? graf?
    if (is.null(dfkrych)){
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      kp=plot_ly(x = c(1, 2), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
          layout(images = list(source = "http://www.chesssetsworld.com/product_images/uploaded_images/choosing.jpg",
                              xref = "x", yref = "y", x = 1, y = 3, sizex = 2, sizey = 2),
                 xaxis = ax, yaxis = ax)
      
    }else{
      p=list()
      
      p[["krych"]]=plot_ly(x=dfkrych$Energy, y=dfkrych[,2], 
                           name = paste("B.",colnames(dfkrych)[2],sep=""), type="scatter", mode = "lines",
                           line = list(width = 1)) %>%
        layout(title = "COHP",
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP bulk"))
      
      if(ncol(dfkrych)>2)
        for (i in 3:ncol(dfkrych))
          p[["krych"]] = add_trace(p[["krych"]], y=dfkrych[,i], name = paste("B.",colnames(dfkrych)[i],sep=""), mode="lines",
                                   line = list(width = 1))
      
      
      p[["stab"]]=plot_ly(x=dfstab$Energy, y=dfstab[,2], 
                          name = colnames(dfstab)[2], type="scatter", mode = "lines",
                          legendgroup = 1, showlegend = T, line = list(width = 1)) %>%
        layout(xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP stable"))
      
      for (i in 3:ncol(dfstab))
        p[["stab"]] = add_trace(p[["stab"]], y=dfstab[,i], 
                                name = colnames(dfstab)[i], mode="lines",
                                legendgroup = i, showlegend = T, line = list(width = 1))
      
      
      p[["nestab"]]=plot_ly(x=dfnestab$Energy, y=dfnestab[,2], 
                            name = colnames(dfnestab)[2], type="scatter", mode = "lines",
                            legendgroup = 1, showlegend = F, line = list(width = 1)) %>%
        layout(xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP unstable"))
      
      for (i in 3:ncol(dfnestab))
        p[["nestab"]] = add_trace(p[["nestab"]], y=dfnestab[,i], 
                                  name = colnames(dfnestab)[i], mode="lines",
                                  legendgroup = i, showlegend = F, line = list(width = 1))
      
      kp=subplot(p, nrows = 3, shareX = T)
    }
      browser()
    kp
  })
  
  # stabilni s bulkem
  output$grafkorStabB = renderPlotly({
    #browser()
    df=val$dfstab
    kor=NULL
    
    x = NULL
    nazvy = dvojice(df)
    for (i in 2:(ncol(df)-1)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        k=NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i],start = 1,stop = 2)=="Ni") {
          k=val$dfkrych[,6]
      } else {
        k=val$dfkrych[,3]
      }
    
      if (!any(is.na(k))){
        kor = c(kor, cor(k, df[,i]))
        x = c(x,colnames(df)[i])
      }
      
    }
    
    plot_ly(x = x,y = kor,type = "bar", source = "bar1")
  })
  
  # nestabilni s bulkem
  output$grafkorNeStabB = renderPlotly({
    # browser()
    df=val$dfnestab
    kor=cor(val$dfkrych[,2], df[,1])
    
    x = colnames(df)[2]
    nazvy = dvojice(df)
    for (i in 3:(ncol(df)-1)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        k=NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Ni") {
        k=val$dfkrych[,6]
      } else {
        k=val$dfkrych[,3]
      }
      
      if (!any(is.na(k))){
        kor = c(kor, cor(k, df[,i]))
        x = c(x,colnames(df)[i])
      }
      
    }
    
    plot_ly(x = x,y = kor,type = "bar", source = "bar2")
  })

  # korelace stabilni s bulk
  output$vyberStabB = renderPlotly({
    s=event_data("plotly_click", source = "bar1")
    # browser()
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                           substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))

      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)

      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }

    p
  })
  
  # korelace nestabilni s bulk
  output$vyberNeStabB = renderPlotly({
    s=event_data("plotly_click", source = "bar2")
    # browser()
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                              substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDTWmindistSTAB = renderPlotly({
    #browser()
    df = val$dfstab
    e = val$dfstab$Energy
    
    d = NULL
    x=NULL
    nazvy = dvojice(df)
    for (i in 2:ncol(df)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        d1 = NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Ni") {
        d1 = val$dfkrych[,6]
      } else {
        d1 = val$dfkrych[,3]
      }
      
      if (!any(is.na(d1))){
        d = c(d,dtwMinLength(d1, df[,i]))
        x = c(x,colnames(df)[i])
      }
    }
    
    plot_ly(x = x, y = d, type = "bar", source = "dtw")
  })
  output$vyberdtw = renderPlotly({
    s=event_data("plotly_click", source = "dtw")
    #browser()
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                              substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))
      
      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDTWmindistNESTAB = renderPlotly({
    
    df=val$dfnestab
    e = val$dfnestab$Energy
    
    d = NULL
    x=NULL
    nazvy = dvojice(df)
    for (i in 2:ncol(df)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        d1 = NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Ni") {
        d1 = val$dfkrych[,6]
      } else {
        d1 = val$dfkrych[,3]
      }
      
      if (!any(is.na(d1))){
        d = c(d,dtwMinLength(d1, df[,i]))
        x = c(x,colnames(df)[i])
      }
    }
    
    plot_ly(x = x, y = d, type = "bar", source = "dtw2")
  })
  output$vyberdtwN = renderPlotly({
    s=event_data("plotly_click", source = "dtw2")
    #browser()
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                              substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDistBodStab = renderPlotly({
    #browser()
    df = val$dfstab
    e = val$dfstab$Energy
    
    d = NULL
    x=NULL
    nazvy = dvojice(df)
    for (i in 2:ncol(df)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        d1 = NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Ni") {
        d1 = val$dfkrych[,6]
      } else {
        d1 = val$dfkrych[,3]
      }
      
      if (!any(is.na(d1))){
        d = c(d,mean(abs(d1-df[,i])))
        x = c(x,colnames(df)[i])
      }
    }
    
    plot_ly(x = x, y = d, type = "bar", source = "dist")
  })
  output$vyberDist = renderPlotly({
    s=event_data("plotly_click", source = "dist")
    #browser()
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                              substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))
      
      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDistBodNestab = renderPlotly({
    #browser()
    df= val$dfnestab[,-1]
    e = val$dfnestab$Energy
    
    d = NULL
    x=NULL
    nazvy = dvojice(df)
    for (i in 2:ncol(df)){
      if(substr(nazvy$x[i-1],start = 1,stop = 2)=="Si" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Si"){
        d1 = NA
      } else if (substr(nazvy$x[i-1],start = 1,stop = 2)=="Ni" & substr(nazvy$y[i-1],start = 1,stop = 2)=="Ni") {
        d1 = val$dfkrych[,6]
      } else {
        d1 = val$dfkrych[,3]
      }
      
      if (!any(is.na(d1))){
        d = c(d,mean(abs(d1-df[,i])))
        x = c(x,colnames(df)[i])
      }
    }
    
    plot_ly(x = x, y = d, type = "bar", source = "dist2")
  })
  output$vyberDistN = renderPlotly({
    s=event_data("plotly_click", source = "dist2")
    
    if (!is.null(s)){
      naz = dvojice(val$dfkrych)
      p=plot_ly(x=val$dfstab$Energy, 
                y=data.frame(val$dfkrych[,c(FALSE, substr(naz$x,1,2)==substr(s$x,1,2) & 
                                              substr(naz$y,1,2)==substr(strsplit(s$x,"[..]")[[1]][3],1,2))])[,1], 
                name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("COHP", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "COHP"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
#outliers Florian
  output$outBarSnini = renderPlotly(({
    #browser()
    nazvy = dvojice(val$dfstab)
    f=val$dfstab[,c(FALSE,substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Ni")]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotSnini = renderPlotly({
    nazvy = dvojice(val$dfstab)
    f=val$dfstab[,c(FALSE,substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Ni")]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))

    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfstab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfstab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfstab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
  
  output$outBarSsini = renderPlotly(({
    #browser()
    nazvy = dvojice(val$dfstab)
    f=val$dfstab[,c(FALSE,(substr(nazvy$x,start = 1,stop = 2)=="Si" & substr(nazvy$y,start = 1,stop = 2)=="Ni") |
                   (substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Si"))]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotSsini = renderPlotly({
    nazvy = dvojice(val$dfstab)
    f=val$dfstab[,c(FALSE,(substr(nazvy$x,start = 1,stop = 2)=="Si" & substr(nazvy$y,start = 1,stop = 2)=="Ni") |
                   (substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Si"))]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfstab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfstab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfstab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
  
  output$outBarNnini = renderPlotly(({
    #browser()
    nazvy = dvojice(val$dfnestab)
    f=val$dfnestab[,c(FALSE,substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Ni")]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotNnini = renderPlotly({
    nazvy = dvojice(val$dfnestab)
    f=val$dfnestab[, c(FALSE,substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Ni")]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfnestab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfnestab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfnestab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
  
  output$outBarNsini = renderPlotly(({
    #browser()
    nazvy = dvojice(val$dfnestab)
    f=val$dfnestab[,c(FALSE,(substr(nazvy$x,start = 1,stop = 2)=="Si" & substr(nazvy$y,start = 1,stop = 2)=="Ni") |
                   (substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Si"))]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotNsini = renderPlotly({
    nazvy = dvojice(val$dfnestab)
    f=val$dfnestab[,c(FALSE,(substr(nazvy$x,start = 1,stop = 2)=="Si" & substr(nazvy$y,start = 1,stop = 2)=="Ni") |
                   (substr(nazvy$x,start = 1,stop = 2)=="Ni" & substr(nazvy$y,start = 1,stop = 2)=="Si"))]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid))
    
    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfnestab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfnestab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfnestab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
}

shinyApp(ui = ui, server = server)

